﻿/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function changePage(page) {
	window.location = page;
	//$.mobile.changePage( page, { transition: "slideleft", rel:"external"});
}

function loadData() {
	if (currentLevel == null || currentLevel == "") currentLevel = 1;
	bindTitles();
	if (jsonQuestions != null && jsonQuestions != "") {
		if (currentLevel > jsonQuestions.length) currentLevel = 1; //Reset for test
		update(jsonQuestions[currentLevel - 1]);
	}
	else {
		$.ajax({
			url: 'question.json',
			dataType: "json",
			success: function (data) {
				jsonQuestions = data;
				update(jsonQuestions[currentLevel - 1]);
			}
		});
	}
}
function update(data) {
    $("#q-image").html('<img class="featured-image" src="' + data.imageUrl + '"/>');
    $("#result-valid").text(data.result);
    var qChar = data.result.split(" ");
    $("#content-result").html("");
    $("#content-candidate").html("");
    for (var i = 0; i < qChar.length; i++) {
        $("#content-result").append('<button class="button" onclick="pressItemSound(); handleResultTap(this);">&nbsp;&nbsp;</button>\n')
    }

    var possible = "ABCDEFGHIKLMNOPQRSTUVXY";

    for (i = qChar.length; i < 14; i++)
        qChar.push(possible.charAt(Math.floor(Math.random() * possible.length)));

    var cChar = shuffle(qChar);

    for (i = 0; i < cChar.length; i++) {
        $("#content-candidate").append('<button class="button" onclick="pressItemSound(); handleCandidateTap(this);">' + cChar[i] + '</button>\n')
    }
    //Reload data for popup
    $("#popup-result-plain-text").html(data.fullResult);
    $("#popup-result-desc").html(data.desc);
}

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

//Main///////////////////////////////////
function handleCandidateTap(obj) {
    var bln = false;
    $("#content-result button:not(.added)").each(function () {
        bln = true;
        $(this).text($(obj).text());
        $(this).addClass("added");
        return false;
    });
    if (bln) {
        $(obj).text("\u00A0");
        $(obj).attr("disabled", true);
        checkResult();
    }
}

function handleResultTap(obj) {
    if ($(obj).hasClass("added")) {
        $("#content-candidate button:disabled").each(function () {
            $(this).text($(obj).text());
            $(this).removeAttr("disabled");
            return false;
        });
        $(obj).removeClass("added");
        $(obj).text("\u00A0");
    }
}
function checkResult() {
    if ($("#content-result button:not(.added)").size() == 0) {
        var enteredVal = "";
        $("#content-result button.added").each(function () {
            enteredVal += " " + $(this).text();
        });
        enteredVal = $.trim(enteredVal).toUpperCase();
        var validVal = $.trim($("#result-valid").text()).toUpperCase();
        if (enteredVal == validVal) {
        	dollar += 20;
            openCorrectPopup();
        }
        else {
        	dollar -= 5;
        	bindTitles();
            openWrongPopup();
        }
    }
}

function clearResult() {
    $("#content-result button.added").each(function () {
        handleResultTap($(this));
    });
}

function hint() {
    var index = 0;
    var obj = "";
    $("#content-result button").each(function () {
        if (!$(this).hasClass("added")) {
            obj = $(this);
            return false;
        }
        index += 1;
    });
    if (obj != "") {
    	dollar -= 3;
        var validVal = $.trim($("#result-valid").text()).split(" ");
        var t = $.trim(validVal[index]).toUpperCase();
        $(obj).text(t);
        $(obj).addClass("added");
        //Find the character in candidate
        $("#content-candidate button:not(:disabled)").each(function () {
            if ($(this).text() == t) {
                $(this).text("\u00A0");
                $(this).attr("disabled", true);
                checkResult();
                return false;
            }
        });
        bindTitles();
    }
}

function bindTitles() {
	$("#main-current-level").html("Level: " + currentLevel);
	$("#main-dollar").html("" + dollar);
}

function next() {
	currentLevel += 1;
	bindTitles();
    loadData();
    $("#popup-correct").popup("close");
}

function openCorrectPopup() {
	var msgs = ["Giỏi vãi !", "Quá thông minh !", "Chính cmn xác !", "Đúng rồi.", "Ngon..", "Biết đáp án à?", "Được đấy.", "Tiếp đê"];
	var ran = Math.floor(Math.random() * msgs.length);
	$("#popup-conform-message").html(msgs[ran]);
    $("#popup-correct").popup('open', {transition:"pop"});
}

function openWrongPopup() {
    $("#popup-wrong").popup("open", {transition:"pop"});
    setTimeout(function () { $("#popup-wrong").popup("close"); }, 1000);
}

